package cn.huaguo.domain.user.service;

import cn.huaguo.domain.user.model.entity.UserEntity;
import cn.huaguo.domain.user.repository.IUserRepository;
import cn.huaguo.types.properties.WeChatProperties;
import cn.huaguo.types.utils.HttpClientUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description 用户业务实现类
 * @Author wangQian
 * @Date 2024/5/13
 */
@Service
public class UserService implements IUserService {
    @Resource
    private WeChatProperties weChatProperties;
    @Resource
    private IUserRepository userRepository;
    private static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Override
    public UserEntity wxLogin(String code) {
        //调用微信接口服务 获取当前登录用户的openid
        //String openid = getOpenid(code);
        String openid = code;
        //判断openid是否为空
        if (null == openid) {
            throw new RuntimeException("openid为空,登录失败");
        }
        UserEntity user = userRepository.queryUserByOpenid(openid);

        if (user == null) {
            //如果用户不存在,则创建新用户
            user = UserEntity.builder()
                    .openid(openid)
                    .build();
            userRepository.addUser(user);
            user = userRepository.queryUserByOpenid(openid);
        }

        return user;
    }

    /**
     * 根据id获取用户信息
     * @param openId
     * @return
     */
    @Override
    public UserEntity getUserById(String openId) {
        return userRepository.queryUserById(openId);
    }

    /**
     * 通过id更新用户接单数量
     * @param openId
     * @param taskCount
     * @return
     */
    @Override
    public void updateUserTaskCount(String openId, String taskCount) {
        userRepository.updateUserTaskCount(openId, taskCount);
    }

    private String getOpenid(String code){
        Map<String,String> map = new HashMap<>();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN, map);

        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        return openid;
    }
}
